package com.yyaccp.hncc.smsg.service.impl;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.yyaccp.hncc.smsg.service.ShortMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 容联云通讯短信实现
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/9/8.
 */
@Service("cloopenSms")
@Slf4j
@ConditionalOnProperty(name = "sms.provider", havingValue = "cloopen")
public class ShortMessageServiceCloopenImpl implements ShortMessageService {
    @Value("${cloopen.serverIp}")
    private String serverIp;
    @Value("${cloopen.accountSId}")
    private String accountSId;
    @Value("${cloopen.accountToken}")
    private String accountToken;
    @Value("${cloopen.appId}")
    private String appId;
    @Value("${cloopen.serverPort}")
    private String serverPort;

    @Value("${sms.cloopen.validCodeTemplateId}")
    private String validCodeTemplateId;

    @Override
    public String sendValidCodeMessage(String phoneNumbers, String code) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("code", code);
        return sendMessage(phoneNumbers,validCodeTemplateId, paramsMap);
    }

    public String sendMessage(String phoneNumbers,String templateId, Map<String, String> paramsMap) {
        String resultMessage = SUCCESS;
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phoneNumbers;
        String[] datas = Arrays.stream(paramsMap.values().toArray())
                .toArray(String[]::new);
//        String subAppend="1234";  //可选 扩展码，四位数字 0~9999
//        String reqId="fadfafas";  //可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
//        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas,subAppend,reqId);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            log.info("响应结果{}", data);
        }else{
            //异常返回输出错误码和错误信息
            resultMessage = "错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg");
            log.warn(resultMessage);
        }
        return resultMessage;
    }
}
